#include <unordered_map>
#include <vector>

using namespace std;

class Solution
{
public:
    vector<int> intersect(vector<int> &nums1, vector<int> &nums2)
    {
        vector<int> ret;
        unordered_map<int, int> m1, m2;
        for (auto e : nums1)
        {
            ++m1[e];
        }
        for (auto e : nums2)
        {
            ++m2[e];
        }

        for (auto e : m2)
        {
            while (m1.count(e.first) && m2.count(e.first))
            {
                ret.push_back(e.first);
                m1[e.first]--;
                m2[e.first]--;
                if (m1[e.first] == 0 || m2[e.first] == 0)
                {
                    break;
                }
            }
        }
        return ret;
    }
};

int main()
{
    Solution a;
    vector<int> num1 = {1, 2, 2, 1}, num2 = {2, 2};
    a.intersect(num1, num2);
    return 0;
}